package other.xsy.pms;

import com.alibaba.fastjson.JSONArray;
import com.rkhd.platform.sdk.data.model.Opportunity;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.xsy.pms.utils.PromotionApiUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 删除业务机会后进行重新推送PMS
 * @Author 黎炎松
 * 2024-09-23 10:35
 */
public class DeleteOpportunityPush implements Trigger {

    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "删除业务机会后重新推送PMS ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Opportunity opportunity = (Opportunity) xObject;
            dataResultList.add(cancelPush(opportunity));
        }
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    /**
     * 删除业务机会后作废推送
     * @param opportunity
     */
    public DataResult cancelPush(Opportunity opportunity){
        try {
            logger.info(LOGGER_MSG + " 处理开始");

            SyncOpportunityToPmsTrigger syncOpt = new SyncOpportunityToPmsTrigger();
            // 设置为失效状态
            opportunity.setIsItInvalid__c(2);
            String saleStageName = syncOpt.getSaleStageName(opportunity.getSaleStageId(), opportunity.getEntityType());
            JSONArray pushData = syncOpt.buidlMsg(opportunity, saleStageName);
            logger.info(LOGGER_MSG + " 推送数据:" + pushData);
            PromotionApiUtil.sendToPms(pushData, PromotionApiUtil.getSaleOpportunitiesUrl());

            logger.info(LOGGER_MSG + " 处理结束");
            return new DataResult(true,"校验完成" , opportunity);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " 处理异常");
            return new DataResult(false, "处理异常", opportunity);
        }
    }

}
